// ## jm4bbx
#include "BinaryOperationResultIndexStreamWritterBox.h"
#include "CellStreamExportVisitor.h"

#include "../../common_bbx/tables/BoxDataTable.h"
#include "../../common_bbx/sharedBoxData/BinaryOperationArguments.h"
// ## c++
#include <sstream>
namespace jm4bbx {
	const char* BinaryOperationResultIndexStreamWritterBox::OUTPUT_FORM_PARAM_NAME = "form";
	const char* BinaryOperationResultIndexStreamWritterBox::FORM_PRINT_FIRST = "first";
	const char* BinaryOperationResultIndexStreamWritterBox::FORM_PRINT_SECOND = "second";
	const char* BinaryOperationResultIndexStreamWritterBox::FORM_PRINT_BOTH = "both";

	BinaryOperationResultIndexStreamWritterBox::BinaryOperationResultIndexStreamWritterBox(const BoxParamPack& pack) : StreamWriterBox(pack) {
		format_ = getBoxParameterValue(pack, OUTPUT_FORM_PARAM_NAME, 
			std::string(FORM_PRINT_BOTH));
	}
	void BinaryOperationResultIndexStreamWritterBox::syncMachEtwas() {

		GroupPtr g = getGroupPtr(INPUT_GROUP);
		if (g->isPoisoned() || areSignalsInPoisoned()) {
			getOutputStream().close();
			//sendSignalsOut(true);
			wait4Receive();
			return;
		}
		
		BoxDataTable* r = BinaryOperationArguments<BoxDataTable>::getFirstArgument();
		BoxDataTable* s = BinaryOperationArguments<BoxDataTable>::getSecondArgument();

		getOutputStream().open();

		for (; g->getReadPosition() < g->getReadEnd(); g->moveReadPosition()) {

				std::stringstream stream;

				BinaryOperationResultIndexType value = 
					get_data<BinaryOperationResultIndexPolicyType>(INPUT_COLUMN)[g->getReadPosition()];

				//stream << value;
				if (format_ == FORM_PRINT_FIRST) {						
					write(stream, r, value.firstTableRowIndex_);
				}
				else if (format_ == FORM_PRINT_SECOND) {
					write(stream, s, value.secondTableRowIndex_);
				}
				else if (format_ == FORM_PRINT_BOTH) {
					// namiesto konca riadku ", " a pokracuejem v zapise
					write(stream, r, value.firstTableRowIndex_, ",");						
					write(stream, s, value.secondTableRowIndex_);
				}
				// Naschval najskor do stringstreamu kt. je lokalna premenna
				// pretoze v pripade priameho dumpovania do outputStream_ by
				// mohlo dochadzat k castemu prekryvaniu zapisu pri paralelizacii. 
				getOutputStream() << stream.str();
		}
		//	
		wait4Receive();
	}

	std::ostream& BinaryOperationResultIndexStreamWritterBox::write(std::ostream& stream, BoxDataTable* t, 
		size_t row, const char* lineEnd /*= "\n"*/) {

			stream << t->getLine(row, lineEnd, ",");
			return stream;
	}
} // namespace jm4bbx
